using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Caching;
using log4net;


namespace Ray.Web.Common
{
    public static class CacheHelper
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(CacheHelper));

        public static void RemoveAllCacheItems()
        {
            IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                String key = CacheEnum.Key.ToString();
                HttpRuntime.Cache.Remove(key);
            }
        }


        public static void TouchCacheFile(String pathToCacheFile)
        {
            if (pathToCacheFile == null) return;

            if (File.Exists(pathToCacheFile))
            {
                File.SetLastWriteTimeUtc(pathToCacheFile, DateTime.Now);
            }
            else
            {
                File.CreateText(pathToCacheFile).Close();
            }
        }


        #region SiteSettings

        //public static SiteSettings GetCurrentSiteSettings()
        //{
        //    return GetSiteSettingsFromCache();
        //}


        //private static SiteSettings GetSiteSettingsFromCache()
        //{
    
        //    bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);
        //    string cachekey;

        //    if (useFolderForSiteDetection)
        //    {
        //        string siteFolderName = VirtualFolderEvaluator.VirtualFolderName();
        //        if (siteFolderName.Length == 0) siteFolderName = "root";
        //        cachekey = "SiteSettings_" + siteFolderName;
        //    }
        //    else
        //    {
        //        String hostName = WebUtils.GetHostName();
        //        cachekey = "SiteSettings_" + hostName;
        //    }

        //    if (HttpRuntime.Cache[cachekey] == null)
        //    {
        //        int cacheTimeout;
        //        bool loadFromWebConfigSucceeded =
        //            int.TryParse(ConfigurationManager.AppSettings["SiteSettingsCacheDurationInSeconds"], out cacheTimeout);
        //        if (!loadFromWebConfigSucceeded) cacheTimeout = 120;

        //        RefreshSiteSettingsCache(cachekey, cacheTimeout);
        //    }

        //    // Return SiteSettings object from cache, or null if it is not there for some reason
        //    return HttpRuntime.Cache[cachekey] as SiteSettings;
        //}

        private static void RefreshSiteSettingsCache(String cacheKey, int cacheTimeout)
        {
            //if (HttpContext.Current == null) return;

            //SiteSettings siteSettings = LoadSiteSettings();
            //if (siteSettings == null) return;

            //String pathToCacheDependencyFile = HttpContext.Current.Server.MapPath(
            //    "~/Data/Sites/"
            //    + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
            //    + "/systemfiles/sitesettingscachedependecy.config");

            //if (pathToCacheDependencyFile != null)
            //{
            //    EnsureCacheFile(pathToCacheDependencyFile);
            //}

            //CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);
            
            //DateTime absoluteExpiration = DateTime.Now.AddSeconds(cacheTimeout);
            //TimeSpan slidingExpiration = TimeSpan.Zero;
            //CacheItemPriority priority = CacheItemPriority.Default;
            //CacheItemRemovedCallback callback = null;

            //HttpRuntime.Cache.Insert(
            //    cacheKey,
            //    siteSettings,
            //    cacheDependency,
            //    absoluteExpiration,
            //    slidingExpiration,
            //    priority,
            //    callback);
        }


        //private static SiteSettings LoadSiteSettings()
        //{
        //    if (log.IsDebugEnabled) log.Debug("CacheHelper.cs LoadSiteSettings");

        //    SiteSettings siteSettings = null;

        //    try
        //    {
        //        bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);
        //        string siteFolderName = VirtualFolderEvaluator.VirtualFolderName();
        //        if (useFolderForSiteDetection)
        //        {
        //            Guid siteGuid = SiteFolder.GetSiteGuid(siteFolderName);
        //            siteSettings = new SiteSettings(siteGuid);
        //        }
        //        else
        //        {
        //            siteSettings = new SiteSettings(WebUtils.GetHostName());
        //        }

        //        if (siteSettings.SiteID > -1)
        //        {
        //            siteSettings.SiteRoot = WebUtils.GetSiteRoot();
        //            if (useFolderForSiteDetection)
        //            {
        //                siteSettings.SiteFolderName = siteFolderName;
        //            }
        //            SetCurrentSkinBaseUrl(siteSettings);
        //        }
        //        else
        //        {
        //            siteSettings = null;
        //            log.Error("CacheHelper failed to load siteSettings");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error("Error trying to obtain siteSettings", ex);
        //    }

        //    return siteSettings;
        //}

        //public static List<String> GetBannedIPList()
        //{
        //    //string cachekey = "bannedipaddresses" ;
            
        //    //if (HttpRuntime.Cache[cachekey] == null)
        //    //{
        //    //    List<String> bannedIPs = BannedIPAddress.GetAllBannedIPs();

        //    //    int cacheTimeout = 120;

        //    //    String pathToCacheDependencyFile 
        //    //        = HttpContext.Current.Server.MapPath(
        //    //    "~/Data/bannedipcachedependency.config");

        //    //    if (pathToCacheDependencyFile != null)
        //    //    {
        //    //        EnsureCacheFile(pathToCacheDependencyFile);
        //    //    }

        //    //    CacheDependency cacheDependency 
        //    //        = new CacheDependency(pathToCacheDependencyFile);

        //    //    DateTime absoluteExpiration = DateTime.Now.AddSeconds(cacheTimeout);
        //    //    TimeSpan slidingExpiration = TimeSpan.Zero;
        //    //    CacheItemPriority priority = CacheItemPriority.Default;
        //    //    CacheItemRemovedCallback callback = null;

        //    //    HttpRuntime.Cache.Insert(
        //    //        cachekey,
        //    //        bannedIPs,
        //    //        cacheDependency,
        //    //        absoluteExpiration,
        //    //        slidingExpiration,
        //    //        priority,
        //    //        callback);

        //    //}

        //    //return HttpRuntime.Cache[cachekey] as List<String>;
        //}


        //public static void SetCurrentSkinBaseUrl(SiteSettings siteSettings)
        //{
        //    if (siteSettings == null) return;

        //    string currentSkin = siteSettings.Skin + "/";

        //    if (siteSettings.AllowUserSkins)
        //    {
        //        string skinCookieName = "mojoUserSkin" + siteSettings.SiteID.ToString();

        //        if (CookieHelper.CookieExists(skinCookieName))
        //        {
        //            string cookieValue = CookieHelper.GetCookieValue(skinCookieName);
        //            if (cookieValue.Length > 0)
        //            {
        //                currentSkin = cookieValue + "/";
        //            }
        //        }
        //    }

        //    string skinFolder = WebUtils.GetSiteRoot() + "/Data/Sites/"
        //                        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture) + "/skins/";

        //    siteSettings.SkinBaseUrl = skinFolder + currentSkin;
        //}


        //public static void TouchSiteSettingsCacheDependencyFile()
        //{
        //    if (HttpContext.Current == null) return;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return;

        //    string path = HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/sitesettingscachedependecy.config");

        //    TouchCacheFile(path);
        //}

        #endregion

        //#region MembershipStatistics

        //public static MembershipStatistics GetCurrentMembershipStatistics()
        //{
        //    return GetMembershipStatisticsFromCache();
        //}


        //private static MembershipStatistics GetMembershipStatisticsFromCache()
        //{
        //    String hostName = WebUtils.GetHostName();
        //    string cachekey = "MembershipStatistics_" + hostName;

        //    if (HttpRuntime.Cache[cachekey] == null)
        //    {
        //        int cacheTimeout;
        //        bool loadFromWebConfigSucceeded =
        //            int.TryParse(ConfigurationManager.AppSettings["SiteSettingsCacheDurationInSeconds"], out cacheTimeout);
        //        if (!loadFromWebConfigSucceeded) cacheTimeout = 120;

        //        RefreshMembershipStatisticsCache(cachekey, cacheTimeout);
        //    }

        //    // Return MembershipStatistics object from cache, or null if it is not there for some reason
        //    return HttpRuntime.Cache[cachekey] as MembershipStatistics;
        //}

        //private static void RefreshMembershipStatisticsCache(String cacheKey, int cacheTimeout)
        //{
        //    if (HttpContext.Current == null) return;

        //    MembershipStatistics membershipStatistics = LoadMembershipStatistics();
        //    if (membershipStatistics == null) return;

        //    String pathToCacheDependencyFile 
        //        = GetPathToMembershipStatisticsCacheDependencyFile();

        //    if (pathToCacheDependencyFile != null)
        //    {
        //        EnsureCacheFile(pathToCacheDependencyFile);
        //    }

        //    CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);

        //    DateTime absoluteExpiration = DateTime.Now.AddSeconds(cacheTimeout);
        //    TimeSpan slidingExpiration = TimeSpan.Zero;
        //    CacheItemPriority priority = CacheItemPriority.Default;
        //    CacheItemRemovedCallback callback = null;

        //    HttpRuntime.Cache.Insert(
        //        cacheKey,
        //        membershipStatistics,
        //        cacheDependency,
        //        absoluteExpiration,
        //        slidingExpiration,
        //        priority,
        //        callback);
        //}


        //private static MembershipStatistics LoadMembershipStatistics()
        //{
        //    if (log.IsDebugEnabled) log.Debug("CacheHelper.cs LoadMembershipStatistics");

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return new MembershipStatistics(
        //        siteSettings,
        //        DateTime.Today.ToUniversalTime().AddHours(DateTimeHelper.GetPreferredGMTOffset()));
        //}


        //public static void TouchMembershipStatisticsCacheDependencyFile()
        //{
        //    TouchCacheFile(GetPathToMembershipStatisticsCacheDependencyFile());
        //}

        //private static string GetPathToMembershipStatisticsCacheDependencyFile()
        //{
        //    if (HttpContext.Current == null) return null;
            
        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;
            
        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/membershipstatisticscachedependecy.config");
        //}

        //#endregion

        #region SiteMap/Menu/PageSettings

        //public static void ResetSiteMapCache()
        //{
        //    TouchMenuCacheDependencyFile();
        //    TouchCacheFile(GetPathToSiteMapCacheDependencyFile());
        //}


        //public static string GetPathToSiteMapCacheDependencyFile()
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/" + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture) 
        //        + "/systemfiles/sitemapcachedependecy.config");
        //}
                

        //public static PageSettings GetCurrentPage()
        //{
        //    if (HttpContext.Current == null) return null;

        //    PageSettings currentPage = HttpContext.Current.Items["CurrentPage"] as PageSettings;
        //    if (currentPage == null)
        //    {
        //        currentPage = LoadCurrentPage();
        //        if (currentPage != null)
        //            HttpContext.Current.Items["CurrentPage"] = currentPage;
        //    }
        //    return currentPage;
        //}


        //private static PageSettings LoadCurrentPage()
        //{
        //    if (log.IsDebugEnabled) log.Debug("CacheHelper.cs LoadCurrentPage");

        //    int pageID = WebUtils.ParseInt32FromQueryString("pageid", -1);

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    bool useFolderForSiteDetection
        //        = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);
        //    string virtualFolder = VirtualFolderEvaluator.VirtualFolderName();
                

        //    PageSettings currentPage = new PageSettings(siteSettings.SiteID, pageID);
        //    if (currentPage.SiteID != siteSettings.SiteID)
        //    {   // probably url manipulation trying to use a pageid that
        //        // doesn't belong to the site so just return the home page
        //        currentPage = new PageSettings(siteSettings.SiteID, -1);
        //    }
            
        //    //if (currentPage.SiteID != siteSettings.SiteID)
        //    //{
        //    //    // throwing exceptions is bad for performance, just redirect
        //    //    if (HttpContext.Current != null) WebUtils.SetupRedirect(null, WebUtils.GetSiteRoot());
        //    //    return null;
        //    //}

        //    if (
        //        (useFolderForSiteDetection)
        //        && (virtualFolder.Length > 0)
        //        && (currentPage.Url.StartsWith("~/"))
        //        )
        //    {
        //        currentPage.Url
        //            = currentPage.Url.Replace("~/", "~/" + virtualFolder + "/");
        //    }

        //    if (
        //        (useFolderForSiteDetection)
        //        && (virtualFolder.Length > 0)
        //        && (!currentPage.UseUrl)
        //        )
        //    {
        //        currentPage.Url
        //            = "~/" + virtualFolder + "/Default.aspx?pageid="
        //            + currentPage.PageID.ToString();
        //        currentPage.UseUrl = true;
        //    }


        //    IDataReader reader = Module.GetPageModules(currentPage.PageID);
        //    while (reader.Read())
        //    {
        //        Module m = new Module();
        //        m.ModuleID = Convert.ToInt32(reader["ModuleID"]);
        //        m.ModuleDefID = Convert.ToInt32(reader["ModuleDefID"]);
        //        m.PageID = Convert.ToInt32(reader["PageID"]);
        //        m.PaneName = reader["PaneName"].ToString();
        //        m.ModuleTitle = reader["ModuleTitle"].ToString();
        //        m.AuthorizedEditRoles = reader["AuthorizedEditRoles"].ToString();
        //        m.CacheTime = Convert.ToInt32(reader["CacheTime"]);
        //        m.ModuleOrder = Convert.ToInt32(reader["ModuleOrder"]);
        //        if (reader["EditUserID"] != DBNull.Value)
        //        {
        //            m.EditUserID = Convert.ToInt32(reader["EditUserID"]);
        //        }

        //        string showTitle = reader["ShowTitle"].ToString();
        //        m.ShowTitle = (showTitle == "True" || showTitle == "1");
        //        m.ControlSource = reader["ControlSrc"].ToString();


        //        currentPage.Modules.Add(m);
        //    }
        //    reader.Close();

        //    return currentPage;
        //}


        //public static Collection<PageSettings> GetMenuPages()
        //{
        //    string cachekey;
        //    bool useFolderForSiteDetection = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);

        //    if (useFolderForSiteDetection)
        //    {
        //        string siteFolderName = VirtualFolderEvaluator.VirtualFolderName();
        //        if (siteFolderName.Length == 0) siteFolderName = "root";
        //        cachekey = "MenuPages_" + siteFolderName;
        //    }
        //    else
        //    {
        //        String hostName = WebUtils.GetHostName();
        //        cachekey = "MenuPages_" + hostName;
        //    }

            

        //    if (HttpRuntime.Cache[cachekey] == null)
        //    {
        //        TouchMenuCacheDependencyFile();

        //        int cacheTimeout = 360;
        //        if (ConfigurationManager.AppSettings["MenuCacheDurationInSeconds"] != null)
        //        {
        //            cacheTimeout = int.Parse(ConfigurationManager.AppSettings["MenuCacheDurationInSeconds"]);
        //        }

        //        RefreshMenuCache(cachekey, cacheTimeout);
        //    }

        //    return HttpRuntime.Cache[cachekey] as Collection<PageSettings>;
        //}


        //private static void RefreshMenuCache(String cacheKey, int cacheTimeout)
        //{
        //    if (HttpContext.Current == null) return;

        //    Collection<PageSettings> menuPages = LoadMenuPages();
        //    if (menuPages == null) return;

        //    String pathToCacheDependencyFile = GetPathToMenuCacheDependencyFile();

        //    CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);

        //    DateTime absoluteExpiration = DateTime.Now.AddSeconds(cacheTimeout);
        //    TimeSpan slidingExpiration = TimeSpan.Zero;
        //    CacheItemPriority priority = CacheItemPriority.Default;
        //    CacheItemRemovedCallback callback = null;

        //    HttpRuntime.Cache.Insert(
        //        cacheKey,
        //        menuPages,
        //        cacheDependency,
        //        absoluteExpiration,
        //        slidingExpiration,
        //        priority,
        //        callback);
        //}


        //private static Collection<PageSettings> LoadMenuPages()
        //{
        //    Collection<PageSettings> menuPages 
        //        = new Collection<PageSettings>();
            
        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return menuPages;

        //    bool useFolderForSiteDetection 
        //        = ConfigHelper.GetBoolProperty("UseFoldersInsteadOfHostnamesForMultipleSites", false);
        //    string virtualFolder = VirtualFolderEvaluator.VirtualFolderName();
                
            
        //    IDataReader reader = SiteSettings.GetPageList(siteSettings.SiteID);

        //    int i = 0;
        //    while (reader.Read())
        //    {
        //        PageSettings pageDetails = new PageSettings();
        //        pageDetails.SiteID = siteSettings.SiteID;
        //        pageDetails.PageID = Convert.ToInt32(reader["PageID"]);
        //        pageDetails.ParentID = Convert.ToInt32(reader["ParentID"]);
        //        pageDetails.PageName = reader["PageName"].ToString();
        //        pageDetails.MenuImage = reader["MenuImage"].ToString();
        //        pageDetails.PageOrder = Convert.ToInt32(reader["PageOrder"]);
        //        pageDetails.AuthorizedRoles = reader["AuthorizedRoles"].ToString();
        //        pageDetails.EditRoles = reader["EditRoles"].ToString();
        //        pageDetails.CreateChildPageRoles = reader["CreateChildPageRoles"].ToString();

        //        string u = reader["UseUrl"].ToString();
        //        pageDetails.UseUrl = (u == "True" || u == "1");
        //        pageDetails.Url = reader["Url"].ToString();

        //        string inMenu = reader["IncludeInMenu"].ToString();
        //        pageDetails.IncludeInMenu = (inMenu == "True" || inMenu == "1");

        //        if (
        //            (useFolderForSiteDetection) 
        //            && (virtualFolder.Length > 0)
        //            &&(pageDetails.Url.StartsWith("~/"))
        //            )
        //        {
        //            pageDetails.Url 
        //                = pageDetails.Url.Replace("~/", "~/" + virtualFolder + "/");
        //        }

        //        if (
        //            (useFolderForSiteDetection)
        //            && (virtualFolder.Length > 0)
        //            && (!pageDetails.UseUrl)
        //            )
        //        {
        //            pageDetails.Url
        //                = "~/" + virtualFolder + "/Default.aspx?pageid="
        //                + pageDetails.PageID.ToString();
        //            pageDetails.UseUrl = true;
        //        }

        //        string nw = reader["OpenInNewWindow"].ToString();
        //        pageDetails.OpenInNewWindow = (nw == "True" || nw == "1");
        //        string cm = reader["ShowChildPageMenu"].ToString();
        //        pageDetails.ShowChildPageMenu = (cm == "True" || cm == "1");

        //        string cc = reader["ShowChildBreadCrumbs"].ToString();
        //        pageDetails.ShowChildPageBreadcrumbs = (cc == "True" || cc == "1");
        //        pageDetails.PageIndex = i;

        //        string cf = reader["ChangeFrequency"].ToString();
        //        switch (cf)
        //        {
        //            case "Always":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Always;
        //                break;

        //            case "Hourly":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Always;
        //                break;

        //            case "Daily":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Daily;
        //                break;

        //            case "Monthly":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Monthly;
        //                break;

        //            case "Yearly":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Yearly;
        //                break;

        //            case "Never":
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Never;
        //                break;

        //            case "Weekly":
        //            default:
        //                pageDetails.ChangeFrequency = PageChangeFrequency.Weekly;
        //                break;


        //        }

        //        string smp = reader["SiteMapPriority"].ToString().Trim();
        //        if (smp.Length > 0) pageDetails.SiteMapPriority = smp;
                
        //        if (reader["LastModifiedUTC"] != DBNull.Value)
        //        {
        //            pageDetails.LastModifiedUTC = Convert.ToDateTime(reader["LastModifiedUTC"]);
        //        }

        //        pageDetails.PageGuid = new Guid(reader["PageGuid"].ToString());
        //        pageDetails.ParentGuid = new Guid(reader["ParentGuid"].ToString());


        //        menuPages.Add(pageDetails);
        //        i++;
        //    }
        //    reader.Close();

        //    return menuPages;
        //}


        //public static void TouchMenuCacheDependencyFile()
        //{
        //    TouchCacheFile(GetPathToMenuCacheDependencyFile());
        //}


        //private static string GetPathToMenuCacheDependencyFile()
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/menucachedependecy.config");
        //}

        #endregion

        #region Module Cache

        public static int GetDefaultModuleCacheTime()
        {
            int cacheTime;
            if (!int.TryParse(ConfigurationManager.AppSettings["DefaultModuleCacheDurationInSeconds"], out cacheTime))
                cacheTime = 360;
            return cacheTime;
        }

        //public static String GetPathToCacheDependencyFile(String cacheDependencyKey)
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/" + cacheDependencyKey + "cachedependecy.config");
        //}


        //public static String GetPathToRSSFeedCacheDependencyFile(int moduleID)
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/" + "rssfeed"
        //        + moduleID.ToString(CultureInfo.InvariantCulture) + "cachedependecy.config");
        //}


        //public static String GetPathToRSSFeedCacheDependencyFile(int moduleID, int itemID)
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/"
        //        + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/" + "rssfeed"
        //        + moduleID.ToString(CultureInfo.InvariantCulture)
        //        + "item" + itemID.ToString(CultureInfo.InvariantCulture)
        //        + "cachedependecy.config");
        //}


        //public static void TouchCacheDependencyFile(String cacheDependencyKey)
        //{
        //    if (HttpContext.Current == null) return;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return;

        //    string pathToCacheDependencyFile = HttpContext.Current.Server.MapPath(
        //            "~/Data/Sites/"
        //            + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //            + "/systemfiles/" + cacheDependencyKey + "cachedependecy.config");

        //    TouchCacheFile(pathToCacheDependencyFile);
        //}


        //public static void EnsureCacheFile(String pathToCacheFile)
        //{
        //    if (pathToCacheFile == null) return;

        //    if (!File.Exists(pathToCacheFile))
        //    {
        //        TouchCacheFile(pathToCacheFile);
        //    }
        //}


        #endregion

        #region Theme Cache

        public static void ResetThemeCache()
        {
            //TouchCacheFile(GetPathToThemeCacheDependencyFile());
        }


        //public static string GetPathToThemeCacheDependencyFile()
        //{
        //    if (HttpContext.Current == null) return null;

        //    SiteSettings siteSettings = GetCurrentSiteSettings();
        //    if (siteSettings == null) return null;

        //    return HttpContext.Current.Server.MapPath(
        //        "~/Data/Sites/" + siteSettings.SiteID.ToString(CultureInfo.InvariantCulture)
        //        + "/systemfiles/themecachedependecy.config");
        //}

        //#endregion

        //#region RSS Feed Cache

        //private static string GetRSSEntryCacheName(int ModuleID, string ItemID)
        //{
        //    return "Entries" + ModuleID.ToString(CultureInfo.InvariantCulture) + "i" + ItemID;
        //}
        
        //public static void ClearRSSFeedCache(int moduleID, int feedListCacheTimeout)
        //{
        //    string entryCacheName = "Entries" + moduleID.ToString(CultureInfo.InvariantCulture);
        //    string feedListcacheName = "FeedList" + moduleID.ToString(CultureInfo.InvariantCulture);

        //    if (HttpRuntime.Cache[entryCacheName] != null)
        //    {
        //        HttpRuntime.Cache.Remove(entryCacheName);
        //    }

        //    if (HttpRuntime.Cache[feedListcacheName] != null)
        //    {
        //        HttpRuntime.Cache.Remove(feedListcacheName);
        //    }

        //    //RSSFeed feed = new RSSFeed(ModuleID);

        //    DataTable feedList = GetRSSFeedList(moduleID, feedListCacheTimeout);
        //    foreach (DataRow row in feedList.Rows)
        //    {
        //        entryCacheName = GetRSSEntryCacheName(moduleID, row["ItemID"].ToString());
        //        if (HttpRuntime.Cache[entryCacheName] != null)
        //        {
        //            HttpRuntime.Cache.Remove(entryCacheName);
        //        }
        //    }
        //}


        //public static void ClearRSSFeedCache(int moduleID)
        //{
        //    string entryCacheName = "Entries" + moduleID.ToString(CultureInfo.InvariantCulture);
        //    string feedListcacheName = "FeedList" + moduleID.ToString(CultureInfo.InvariantCulture);

        //    if (HttpRuntime.Cache[entryCacheName] != null)
        //    {
        //        HttpRuntime.Cache.Remove(entryCacheName);
        //    }

        //    if (HttpRuntime.Cache[feedListcacheName] != null)
        //    {
        //        HttpRuntime.Cache.Remove(feedListcacheName);
        //    }


        //    Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleID);
        //    if (moduleSettings.Contains("RSSFeedFeedListCacheTimeoutSetting"))
        //    {
        //        //RSSFeed feed = new RSSFeed(moduleID);
        //        int FeedListCacheTimeout = int.Parse(moduleSettings["RSSFeedFeedListCacheTimeoutSetting"].ToString());
        //        DataTable feedList = GetRSSFeedList(moduleID, FeedListCacheTimeout);
        //        foreach (DataRow row in feedList.Rows)
        //        {
        //            entryCacheName = GetRSSEntryCacheName(moduleID, row["ItemID"].ToString());
        //            if (HttpRuntime.Cache[entryCacheName] != null)
        //            {
        //                HttpRuntime.Cache.Remove(entryCacheName);
        //            }
        //        }
        //    }
        //}


        //public static DataTable GetRSSFeedEntries(
        //    int moduleID,
        //    int entryCacheTimeout, 
        //    int feedListCacheTimeout, 
        //    int maxDaysOld, 
        //    int maxEntriesPerFeed)
        //{
        //    string cacheName = "Entries" + moduleID.ToString(CultureInfo.InvariantCulture);
        //    if (HttpRuntime.Cache[cacheName] == null)
        //    {
        //        RefreshRSSFeedEntryCache(
        //            moduleID,
        //            entryCacheTimeout, 
        //            feedListCacheTimeout, 
        //            maxDaysOld, 
        //            maxEntriesPerFeed, 
        //            String.Empty, 
        //            null, 
        //            CacheItemRemovedReason.DependencyChanged);
        //    }
        //    return (DataTable)HttpRuntime.Cache[cacheName];
        //}


        //public static DataTable GetRSSFeedEntries(
        //    int moduleID,
        //    int itemID, 
        //    int entryCacheTimeout, 
        //    int feedListCacheTimeout, 
        //    int maxDaysOld, 
        //    int maxEntriesPerFeed)
        //{
        //    if (itemID == 0)
        //    {
        //        DataRow dr = GetRSSFeedList(moduleID, feedListCacheTimeout).Rows[0];
        //        itemID = Convert.ToInt32(dr["ItemID"]);

        //    }

        //    string cacheName = GetRSSEntryCacheName(moduleID, itemID.ToString(CultureInfo.InvariantCulture));
        //    if (HttpRuntime.Cache[cacheName] == null)
        //    {
        //        RefreshRSSFeedEntryCache(
        //            moduleID,
        //            itemID, 
        //            entryCacheTimeout, 
        //            feedListCacheTimeout, 
        //            maxDaysOld, 
        //            maxEntriesPerFeed,
        //            "", 
        //            null, 
        //            CacheItemRemovedReason.DependencyChanged);
        //    }
        //    return (DataTable)HttpRuntime.Cache[cacheName];
        //}

        //public static void RefreshRSSFeedEntryCache(
        //    int moduleID,
        //    int entryCacheTimeout,
        //    int feedListCacheTimeout,
        //    int maxDaysOld,
        //    int maxEntriesPerFeed,
        //    string key,
        //    object cacheItem,
        //    CacheItemRemovedReason reason)
        //{
        //    DataTable entries = new DataTable();
        //    entries.Columns.Add("PubDate", Type.GetType("System.DateTime"));
        //    entries.Columns.Add("Author", Type.GetType("System.String"));
        //    entries.Columns.Add("Title", Type.GetType("System.String"));
        //    entries.Columns.Add("Description", Type.GetType("System.String"));
        //    entries.Columns.Add("BlogUrl", Type.GetType("System.String"));
        //    entries.Columns.Add("Link", Type.GetType("System.String"));


        //    DateTime CutoffDate = DateTime.Now.AddDays(-maxDaysOld);

        //    foreach (DataRow dr in GetRSSFeedList(moduleID, feedListCacheTimeout).Rows)
        //    {
        //        int entriesAdded = 0;
        //        try
        //        {
        //            RssFeed feed = RssFeed.Read((string)dr["RssUrl"]);

        //            if (feed.Channels.Count > 0)
        //            {
        //                foreach (RssItem item in feed.Channels[0].Items)
        //                {
        //                    if ((item.PubDate >= CutoffDate) || (maxDaysOld == 0))
        //                    {

        //                        if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0))
        //                        {
        //                            DataRow entry = entries.NewRow();
        //                            entry["PubDate"] = item.PubDate;
        //                            entry["Author"] = dr["Author"];
        //                            entry["Title"] = item.Title;
        //                            entry["Description"] = item.Description;
        //                            entry["BlogUrl"] = dr["Url"];
        //                            entry["Link"] = item.Link;



        //                            entries.Rows.Add(entry);
        //                        }

        //                        entriesAdded += 1;

        //                    }

        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            if (log.IsErrorEnabled)
        //            {
        //                string logMsg = String.Format("There was a problem trying to read the feed for entry {0}, url {1}.  Ignoring.", entriesAdded, dr["RssUrl"]);
        //                log.Error(logMsg, ex);
        //            }
        //        }

        //    }

        //    String pathToCacheDependencyFile = GetPathToRSSFeedCacheDependencyFile(moduleID);
        //    EnsureCacheFile(pathToCacheDependencyFile);
        //    CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);

        //    HttpRuntime.Cache.Insert(
        //        "Entries" + moduleID.ToString(CultureInfo.InvariantCulture),
        //        entries,
        //        cacheDependency,
        //        DateTime.Now.AddMinutes(entryCacheTimeout),
        //        TimeSpan.Zero,
        //        CacheItemPriority.Default,
        //        null);

        //}


        //public static void RefreshRSSFeedEntryCache(
        //    int moduleID,
        //    int itemID,
        //    int entryCacheTimeout,
        //    int feedListCacheTimeout,
        //    int maxDaysOld,
        //    int maxEntriesPerFeed,
        //    string cacheKeyey,
        //    object feedItem,
        //    CacheItemRemovedReason Reason)
        //{
        //    DataTable entries = new DataTable();
        //    //entries.Columns.Add("ItemID", int);
        //    entries.Columns.Add("Author", Type.GetType("System.String"));
        //    entries.Columns.Add("Title", Type.GetType("System.String"));
        //    entries.Columns.Add("Description", Type.GetType("System.String"));
        //    entries.Columns.Add("BlogUrl", Type.GetType("System.String"));
        //    entries.Columns.Add("Link", Type.GetType("System.String"));
        //    entries.Columns.Add("PubDate", Type.GetType("System.DateTime"));

        //    DateTime CutoffDate = DateTime.Now.AddDays(-maxDaysOld);
        //    RSSFeed singleFeed;

        //    singleFeed = new RSSFeed(moduleID, itemID);
        //    int entriesAdded = 0;
        //    try
        //    {
        //        RssFeed feed = RssFeed.Read(singleFeed.RssUrl);

        //        foreach (RssItem item in feed.Channels[0].Items)
        //        {
        //            if ((item.PubDate >= CutoffDate) || (maxDaysOld == 0))
        //            {

        //                if ((entriesAdded < maxEntriesPerFeed) || (maxEntriesPerFeed == 0))
        //                {
        //                    DataRow entry = entries.NewRow();
        //                    entry["Author"] = singleFeed.Author;
        //                    entry["Title"] = item.Title;
        //                    entry["Description"] = item.Description;
        //                    entry["BlogUrl"] = singleFeed.Url;
        //                    entry["Link"] = item.Link;
        //                    entry["PubDate"] = item.PubDate;
        //                    entries.Rows.Add(entry);

        //                    entriesAdded += 1;
        //                }

                        
        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        if (log.IsErrorEnabled)
        //        {
        //            string logMsg = String.Format("There was a problem trying to read the entries for url {0}.  Ignoring.", singleFeed.RssUrl);
        //            log.Error(logMsg, ex);
        //        }

        //    }

        //    String pathToCacheDependencyFile = GetPathToRSSFeedCacheDependencyFile(moduleID, itemID);
        //    EnsureCacheFile(pathToCacheDependencyFile);
        //    CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);

        //    HttpRuntime.Cache.Insert(
        //        GetRSSEntryCacheName(moduleID, itemID.ToString(CultureInfo.InvariantCulture)),
        //        entries,
        //        cacheDependency,
        //        DateTime.Now.AddMinutes(entryCacheTimeout),
        //        TimeSpan.Zero,
        //        CacheItemPriority.Default,
        //        null);

        //}

        //public static DataTable GetRSSFeedList(int moduleID, int feedListCacheTimeout)
        //{
        //    string cacheName = "FeedList" + moduleID.ToString(CultureInfo.InvariantCulture);
        //    if (HttpRuntime.Cache[cacheName] == null)
        //    {
        //        RefreshRSSFeedListCache(
        //            moduleID,
        //            feedListCacheTimeout,
        //            String.Empty,
        //            null,
        //            CacheItemRemovedReason.DependencyChanged);
        //    }
        //    return (DataTable)HttpRuntime.Cache[cacheName];
        //}

        public static void RefreshRSSFeedListCache(
            int moduleID,
            int feedListCacheTimeout, 
            string cacheKey, 
            object o, 
            CacheItemRemovedReason Reason)
        {

            //DataTable members = RSSFeed.GetFeeds(moduleID).Tables[0];
            //string cacheName = "FeedList" + moduleID.ToString(CultureInfo.InvariantCulture);

            //String pathToCacheDependencyFile = GetPathToRSSFeedCacheDependencyFile(moduleID);
            //EnsureCacheFile(pathToCacheDependencyFile);
            //CacheDependency cacheDependency = new CacheDependency(pathToCacheDependencyFile);

            //HttpRuntime.Cache.Insert(
            //    cacheName,
            //    members,
            //    cacheDependency,
            //    DateTime.Now.AddMinutes(feedListCacheTimeout),
            //    TimeSpan.Zero,
            //    CacheItemPriority.Default,
            //    null);
        }


        #endregion

    }
}
